<script setup>
import { computed, watch, nextTick, ref } from 'vue';
import { useStore } from 'vuex';
import { useRoute, onBeforeRouteUpdate, useRouter } from 'vue-router';
// 引组件
import MyButton from '@/components/mybutton.vue';
// import { isDark } from '~/composables/dark';
const route = useRoute();
const store = useStore();
const router = useRouter();
// store.dispatch('category/updateSubCategoryGoodsList', route.path.split('/')[3]);
const subcategory = computed(() => store.state.category.subCategoryList);
// // 获取当前种类上的商品

const currentPage = ref(1);

const params = {
  brandId: undefined,
  attrs: [],
  page: currentPage.value,
  pageSize: 10,
  categoryId: route.params.id,
};
function init(to) {
  params.categoryId = to.params.id;
  store.dispatch('category/updateSubCategoryGoods', params);
  store.dispatch('category/updateSubCategoryList', to.params.id);
}

// 初始化请求
init(route);
// 路由id变化时, 重新请求
onBeforeRouteUpdate(init);


const subCategoryGoods = computed(() => store.state.category.subCategoryGoods);
// 记录
let observer = null;
let lastObserver = null;

const hasNext = computed(() => subCategoryGoods.value.pages > currentPage.value);

watch(subCategoryGoods, async () => {
  if (!hasNext.value) {
    return;
  }
  await nextTick();
  // 取消上一轮的观察
  if (observer) {
    observer.unobserve(lastObserver);
  }
  // 当clothes滚动到视野中时, dispatch
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        // 应该自己写的内容
        params.page = ++currentPage.value;
        store.dispatch('category/updateSubCategoryGoods', params);
      }
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5,
    },
  );
  lastObserver = document.querySelector('.boxtwo:last-child');
  // 启动观察clothes.value是否进入视野
  observer.observe(lastObserver);
});
// 跳转到商品详情页
function shoppingdetails(id) {
  // 跳转到商品详情页
  router.push({
    path: '/goods/' + id,
  });
  store.dispatch('cart/updateMember', id);
}
// 引入名为subCategoryFilters的getters
const subCategoryFilters = ref([]);
const subCategoryFiltersAttrs = ref([]);

watch(
  () => store.getters['category/subCategoryFilters'],
  () => {
    subCategoryFilters.value = store.getters['category/subCategoryFilters'].map((d) => ({
      ...d,
      properties: [
        {
          id: 'all',
          name: '全部',
        },
        ...d.properties,
      ],
    }));
    subCategoryFiltersAttrs.value = store.getters['category/subCategoryFilters'].map((d) => ({
      groupName: d.name,
      propertyName: '全部',
    }));
  },
);

async function onFilterChange() {
  await nextTick();
  const attrs = subCategoryFiltersAttrs.value.filter((d, i) => d.propertyName !== '全部' && i > 0);
  currentPage.value = 1;
  params.brandId = store.state.category.subCategoryList.brands.find((b) => b.name === subCategoryFiltersAttrs.value[0].propertyName)?.id || null;
  params.attrs = attrs;
  params.page = 1;
  store.dispatch('category/updateSubCategoryGoods', params);
}
// 传事件
const sortType = ref('');
function onClick(value) {
  sortType.value = value;
}
</script>

<template>
  <el-breadcrumb separator-icon="ArrowRight" class="crumbs wapper">
    <el-breadcrumb-item :to="{ path: '/homepage' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>{{ subcategory.name }}</el-breadcrumb-item>
  </el-breadcrumb>
  <div class="conter">
    <div class="heard wapper">
      <div class="vessel">
        <el-form>
          <el-form-item v-for="(item, i) in subCategoryFilters" :key="item.id" :label="item.name">
            <el-radio-group v-model="subCategoryFiltersAttrs[i].propertyName" @change="onFilterChange">
              <el-radio v-for="property in item.properties" :key="property.id" :label="property.name">
                {{ property.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="fotter wapper">
      <div class="sub-sort">
        <el-row class="sub-sort-left">
          <el-button >默认排序</el-button>
          <el-button >最新商品</el-button>
          <el-button >最高人气</el-button>
          <el-button>评论最多</el-button>
          <my-button
            v-model:value="sortType"
            @change="onClick"
          >
            价格排序
          </my-button>
        </el-row>
        <div>
          <el-checkbox label="仅显示有货商品" size="large" text-color="#27ba9b" />
          <el-checkbox label="仅显示特惠商品" size="large" fill="red" />
        </div>
      </div>
      <div class="card">
        <div
          class="boxtwo"
          v-for="item in subCategoryGoods.items"
          :key="item.id"
          @click="shoppingdetails(item.id)"
        >
          <img :src="item.picture" alt="" />
          <p>{{ item.name }}</p>
          <p>{{ item.desc }}</p>
          <p>¥{{ item.price }}</p>
        </div>
      </div>
      <div class="show wapper" v-if="!hasNext">
        <div class="box">
          <img src="../../../assets/没有更多了.png" alt="">
          <span>亲，没有更多了</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scope>
// 面包屑
.crumbs {
  padding: 0;
  transform: translateY(50px);
}

// 版心
.wapper {
  margin: 0 auto;
  width: 1240px;
}

// 清除a标签默认样式
a {
  text-decoration: none;
  color: #333;
}

// 容器
.conter {
  background-color: #f5f5f5;
  padding-top: 100px;
  .el-radio__input {
      display: none;
    }
  // 头部
  .heard {
    background: #fff;
    flex-wrap: wrap;

    .vessel {
      padding-left: 20px;
      // padding-top: 10px;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // &:visited{
      //   color:#27ba9b
      // }
      .left {
        color: #999;
        width: 80px;
        height: 50px;
        line-height: 50px;
        font-size: 14px;
      }

      .right {
        flex: 1;

        .for {
          padding-right: 25px;
          font-size: 14px;
          line-height: 50px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 120px;

          a:hover {
            color: #27ba9b;
          }
        }
      }

      a:nth-child(1) {
        color: #27ba9b;
        padding: 0;
        font-size: 14px;
        line-height: 50px;
      }

      a:nth-child(2) {
        padding-left: 25px;
        padding-right: 25px;
        font-size: 14px;

        &:hover {
          color: #27ba9b;
        }
        // &:visited {
        //   color: #27ba9b
        // }
      }


    }
  }

  // 底部
  .fotter {
    margin-top: 20px;
    background-color: #fff;

    .sub-sort {
      padding: 20px;
      display: flex;
      // outline: 1px solid red;
      // align-items: center;
      justify-content: space-between;

      .sub-sort-left {
        width:200px;
        display: flex;
        flex: 1;
        align-items: center;
          .el-button:focus{
            background:#27bb9a !important;
            border-color: #27bb9a!important;
            color: #FFF !important;
            opacity: 0.8;
          }
          .el-button:hover{
          background-color: #fff !important;
          color: #606266 !important;
          border-color: #DCDFE6 !important;
          }
      }

      .screen {
        color: #999;

        i {
          transform: translateY(4px);
        }
      }
    }

    .card {
      margin-left: 20px;

      // padding-bottom: 50px;
      .boxtwo {
        // outline: 1px solid red;
        display: inline-block;
        text-align: center;
        width: 220px;
        height: 300px;
        margin-right: 23px;
        margin-bottom: 20px;
        transition: all 0.2s;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 20px 80px rgba(48, 49, 51, 0.15);
          cursor: pointer;
        }

        img {
          padding-top: 20px;
          height: 160px;
          width: 160px;
          margin: 0  auto;
        }

        p {
          margin: 0 auto;
          text-align: center;
          font-size: 16px;
          color: black;
          padding-top: 20px;
          width: 160px;
          /* 有限的空间才能有溢出的可能 */
          overflow: hidden;
          -webkit-line-clamp: 1;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          word-break: break-all;
          line-break: anywhere;
        }

        p:nth-child(3) {
          font-size: 14px;
          color: #999;
          padding-top: 8px;
        }

        p:last-child {
          color: #cf4444;
          font-size: 20px;
          padding-top: 10px;
        }

      }
    }

    .show {
      // outline: 1px solid red;
      .box {
        padding-left: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
        // outline: 1px solid red;

        span {
          color: #999;
        }
      }
    }
  }
}
</style>
